<?php namespace Phpcmf\Model\Bdtj;

class Bdtj extends \Phpcmf\Model
{

    private $zzconfig;

    // 配置信息
    public function getConfig() {

        if ($this->zzconfig) {
            return $this->zzconfig;
        }

        if (is_file(WRITEPATH.'config/bdtj.php')) {
            $this->zzconfig = require WRITEPATH.'config/bdtj.php';
            return $this->zzconfig;
        }

        return [];
    }

    // 配置信息
    public function setConfig($data) {

        \Phpcmf\Service::L('Config')->file(WRITEPATH.'config/bdtj.php', '站长配置文件', 32)->to_require($data);

    }

    // 站点列表
    public function get_site_list() {

        $cfg = $this->getConfig();
        if (!isset($cfg['bdtj']['user'])) {
            return dr_return_data(0, '没有设置百度统计接口');
        }

        $url = 'https://api.baidu.com/json/tongji/v1/ReportService/getSiteList';
        return $this->_post_data($url, [
            'header' => [
                "username" => $cfg['bdtj']['user'], //您的用户名
                "password" => $cfg['bdtj']['pass'], //您的密码
                "token" => $cfg['bdtj']['token'],    //您的token
                "account_type" => 1
            ]
        ]);

    }

    // 网站概况(趋势数据)
    public function get_overview($id) {

        $cfg = $this->getConfig();
        if (!isset($cfg['bdtj']['user'])) {
            return dr_return_data(0, '没有设置百度统计接口');
        }

        $url = 'https://api.baidu.com/json/tongji/v1/ReportService/getData';
        $rt = $this->_post_data($url, [
            'header' => [
                "username" => $cfg['bdtj']['user'], //您的用户名
                "password" => $cfg['bdtj']['pass'], //您的密码
                "token" => $cfg['bdtj']['token'],    //您的token
                "account_type" => 1
            ],
            'body' => [
                'site_id' => $id,
                'start_date' => date("Ymd",strtotime("-1 day")),
                'end_date' => date('Ymd'),
                'metrics' => 'pv_count,visitor_count,ip_count',
                'method' => 'overview/getTimeTrendRpt',
            ]
        ]);
        if (!$rt['code']) {
            return dr_return_data(0, $rt['msg']);
        }
        $r = [];
        foreach ($rt['data'][0]['result']['items'][0] as $i => $day) {
            $r[$i] = [
                'time' => $day[0],
                'pv' => $rt['data'][0]['result']['items'][1][$i][0],
                'uv' => $rt['data'][0]['result']['items'][1][$i][1],
                'ip' => $rt['data'][0]['result']['items'][1][$i][2],
            ];
        }

        return dr_return_data(1, '', $r);
    }

    // 从url获取json数据
    private function _post_data($url, $param = []) {

        $name = md5($url.dr_array2string($param));
        $cache = \Phpcmf\Service::L('cache')->get_data($name);
        if ($cache) {
            return dr_return_data(1, '', $cache);
        }

        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
        curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode($param, JSON_UNESCAPED_UNICODE));
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        $response = curl_exec ( $ch );
        if ($error=curl_error($ch)){
            return dr_return_data(0, $error);
        }
        curl_close($ch);
        $data = json_decode($response, true);
        if (isset($data['header']['desc']) && $data['header']['desc'] == 'success') {
            // 存储缓存
            \Phpcmf\Service::L('cache')->set_data($name, $data['body']['data'], 300);
            return dr_return_data(1, 'ok', $data['body']['data']);
        }
        $msg = $data['header']['desc'];
        if ($data['header']['failures']) {
            foreach ($data['header']['failures'] as $t) {
                $msg.= '   '.$t['message'];
            }
        }

        return dr_return_data(0, $msg);
    }
}